﻿using SYJ.Common.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;


namespace SYJ.Filter
{
    /// <summary>
    /// 登陆验证过滤器
    /// </summary>
    public class LoginAttribute : AuthorizeAttribute
    {
        public Func<AuthorizationContext, bool> IsNotAuthorized { get; set; }
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            //如果用户方位的Action带有SkipAuthorizeAttribute，则不进行授权验证
            if (filterContext.ActionDescriptor.IsDefined(typeof(SkipAuthorizeAttribute), false))
            {
                return;
            }
            
            try
            {
                if (!filterContext.HttpContext.User.Identity.IsAuthenticated || HttpContext.Current.Session["UserKey"]==null) {
                    filterContext.Result = new RedirectResult(FormsAuthentication.LoginUrl);
                }
                //if (IsNotAuthorized != null && !IsNotAuthorized(filterContext))
                //{
                //    filterContext.Result = new RedirectResult(FormsAuthentication.LoginUrl);
                //}
            }
            catch (Exception ex)
            {
                //AppContext.Logger.Info(ex);
                throw;
            }

            base.OnAuthorization(filterContext);
        }
    }
}